import axios from 'axios'
import router from '../router'
import qs from 'qs';
import { showToast, showLoadingToast, showDialog } from 'vant'

axios.defaults.baseURL = import.meta.env.VITE_BASE_URL

let loadingToast = null
axios.interceptors.request.use(config => {
	let showLoading = true

  // 不显示加载动画
  if (config.url.includes('hideLoading=true')) showLoading = false
	if (showLoading){
    let message = '加载中...';
    if (config.url.includes('/speaker/portraitV2')) message = '智能一键生成头像中...'
    if (config.url.includes('/speaker/uploadSpeakerAvatar')) message = '头像上传中...'
		loadingToast = showLoadingToast({
			message,
			forbidClick: true,
			loadingType: 'spinner',
			duration: 0
		})
	}

	const token = sessionStorage.getItem('v1@CacheToken')
	if (token) config.headers.token = JSON.parse(token)['token']
  const tenantCode = sessionStorage.getItem('tenantCode') || '1731596052865302530'
  if (tenantCode) config.headers.tenantCode = tenantCode

	return config
}, error => {
	loadingToast && loadingToast.close()
	showToast('网络超时，请检查网络情况')
	return Promise.reject(error)
})

axios.interceptors.response.use(response => {
	if (response.config.url.endsWith('/policy/saveVideoLog')) {
		return response
	}
	loadingToast && loadingToast.close()
	if (response.data.code) {
		switch (response.data.code) {
			case 10021:
				showDialog({
					title: '提示',
					message: response.data.msg
				}).then(() => {
					sessionStorage.removeItem('userInfo')
					sessionStorage.removeItem('token')
					router.replace('/login')
				})
				break
			default:
				showToast(response.data.msg)
		}
	}

	return response
}, error => {
	loadingToast && loadingToast.close()
	showToast('请求超时，请稍后重试')
	return Promise.reject(error)
})

export default {
	get (url, params) {
		return new Promise((resolve, reject) => {
			axios.get(url, { params })
				.then(res => resolve(res.data))
				.catch(err => reject(err))
		})
	},
	post (url, data, options = {}) {
		return new Promise((resolve, reject) => {
			axios.post(`${url}`, data)
				.then(res => resolve(res.data))
				.catch(err => reject(err))
		})
	},
	postMap (url, data) {
		return new Promise((resolve, reject) => {
			axios.post(url,{...data.data},{
				headers: {
					"Content-Type": "application/x-www-form-urlencoded"
				}
			}).then(res => resolve(res.data)).catch(err => reject(err))
		})
	}
}
